<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <el-card class="box-card">
    <h1 class="container">菜品中心</h1>
    <div class="manage-header">
      <!-- form 搜索区域 -->
      <el-form
        :inline="true"
        :model="SearchForm"
        class="demo-form-inline"
        ref="searchFormRef"
        size="small"
      >
        <el-form-item label="时间范围" prop="time">
          <el-date-picker
            v-model="SearchTimeValue"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="菜名" prop="name">
          <el-input
            v-model="SearchForm.name"
            placeholder="请输入菜名"
          ></el-input>
        </el-form-item>
        <el-form-item label="菜品类型" prop="type">
          <el-select v-model="SearchForm.type" placeholder="请选择类型">
            <el-option label="西餐" value="1"></el-option>
            <el-option label="中餐" value="2"></el-option>
            <el-option label="快餐" value="3"></el-option>
            <el-option label="饮品" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select
            v-model="SearchForm.state"
            placeholder="请选择类型"
            defaultV
          >
            <el-option label="开启" value="true"></el-option>
            <el-option label="关闭" value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch(SearchForm)"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button @click="onSearchClear()">重置</el-button>
        </el-form-item>
      </el-form>

      <el-button
        type="primary"
        @click="handAdd"
        style="height: 40px"
        size="small"
      >
        + 新增
      </el-button>
    </div>

    <el-table
      :data="
        tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
      "
      style="width: 100%"
      align="center"
    >
      <el-table-column prop="updateTime" label="更新时间" width="120">
      </el-table-column>
      <el-table-column prop="name" label="菜名"> </el-table-column>
      <el-table-column prop="imgaes" label="图片">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.imgaes"
            style="width: 50px; height: 50px"
            :src="scope.row.imgaes[0]"
            :preview-src-list="scope.row.imgaes"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格"> </el-table-column>
      <el-table-column prop="special" label="特点"> </el-table-column>
      <el-table-column label="类型" prop="type">
        <template slot-scope="scope">
          <div>
            {{ FoodTypeMap(scope.row.type) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="num" label="剩余份数"> </el-table-column>
      <el-table-column prop="state" label="状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.state"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="changeSwitch(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="
              isEidtModelVisible = true;
              onEdit(scope.row);
            "
            icon="el-icon-edit"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="onDelete(scope.row)"
            icon="el-icon-delete"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[2, 5, 10, 15]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page_num"
      >
      </el-pagination>
    </div>
    <!-- 编辑弹窗 -->
    <el-dialog title="修改信息" :visible.sync="isEidtModelVisible" width="60%">
      <el-form
        ref="EidtFormRef"
        :label-position="labelPosition"
        label-width="80px"
        :model="EidtForm"
        :rules="editRules"
      >
        <el-form-item label="菜名" prop="name">
          <el-input v-model="EidtForm.name"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="EidtForm.price"></el-input>
        </el-form-item>
        <el-form-item label="特点" prop="special">
          <el-input v-model="EidtForm.special"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="EidtForm.type">
            <el-radio :label="'1'">快餐</el-radio>
            <el-radio :label="'2'">面条</el-radio>
            <el-radio :label="'3'">西餐</el-radio>
            <el-radio :label="'4'">饮品</el-radio>
            <el-radio :label="'5'">中餐</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="剩余份数" prop="num">
          <el-input v-model="EidtForm.num"></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <el-upload
            action="#"
            list-type="picture-card"
            :limit="1"
            :auto-upload="false"
            :on-change="(file) => handleSuccess(file, EidtForm.foodId)"
          >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{ file }">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url"
                alt=""
              />
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isEidtModelVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="
            isEidtModelVisible = false;
            onEditBtn(EidtForm);
          "
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 新增弹出框 -->
    <el-dialog title="新增菜品" :visible.sync="isAddModelVisible" width="60%">
      <!-- 用户的表单信息 -->
      <el-form
        ref="AddFormRef"
        :rules="addRules"
        :model="AddForm"
        label-width="80px"
      >
        <el-form-item label="菜名" prop="name">
          <el-input v-model="AddForm.name" placeholder="请输入菜名"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="AddForm.price" placeholder="请输入价格"></el-input>
        </el-form-item>
        <el-form-item label="特点" prop="special">
          <el-input
            v-model="AddForm.special"
            placeholder="请输入菜品特点"
          ></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="AddForm.type">
            <el-radio :label="'1'">快餐</el-radio>
            <el-radio :label="'2'">面条</el-radio>
            <el-radio :label="'3'">西餐</el-radio>
            <el-radio :label="'4'">饮品</el-radio>
            <el-radio :label="'5'">中餐</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="剩余份数" prop="num">
          <el-input v-model="AddForm.num"></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <el-upload action="#" list-type="picture-card" :auto-upload="false">
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{ file }">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url"
                alt=""
              />
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 用户的表单信息 -->

      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddModelVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>
  


<script>
export default {
  created() {
    this.getUserList();
  },
  data() {
    return {
      disabled: false,
      typeList: [],
      // 编辑弹窗状态
      isEidtModelVisible: false,
      // 新增弹窗
      isAddModelVisible: false,
      labelPosition: "right",
      // 订单信息
      tableData: [],
      // 分页
      page_num: 0,
      pageSize: 10,
      currentPage: 1,
      // 搜索form
      SearchForm: {
        name: "",
        type: "",
        state: "",
      },
      // 编辑form
      EidtForm: {},
      // 新增form
      AddForm: {},
      // 表单验证规则
      addRules: {
        name: [{ required: true, message: "请输入菜名" }],
        price: [{ required: true, message: "请输入价格" }],
        special: [{ required: true, message: "请输入菜品特点" }],
        num: [{ required: true, message: "请输入剩余菜品数量" }],
      },
      editRules: {
        name: [{ required: true, message: "请输入菜名" }],
        price: [{ required: true, message: "请输入价格" }],
        special: [{ required: true, message: "请输入菜品特点" }],
        num: [{ required: true, message: "请输入剩余菜品数量" }],
      },
      // 搜索日期
      SearchTimeValue: [
        new Date(2000, 10, 10, 10, 10),
        new Date(2000, 10, 11, 10, 10),
      ],
    };
  },
  computed: {
    FoodTypeMap() {
      return (value) => {
        const data = {
          1: "快餐",
          2: "面条",
          3: "西餐",
          4: "饮品",
          5: "中餐",
        };
        return data[value];
      };
    },
  },
  methods: {
    // 状态按钮
    changeSwitch(value) {
      this.$confirm("此操作将修改菜品状态, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: "true",
      })
        .then(() => {
          this.switchUrl(value);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消修改",
          });
        });
      value.state = !value.state;
    },
    async switchUrl(value) {
      const { id, state } = value;
      let switchNum = state ? 0 : 1;
      const { data: res } = await this.$http.post("/admin/foodCenter/switch", {
        id,
        state: switchNum,
      });
      if (res.code !== 200) {
        this.$message.error("修改失败");
        return;
      }
      this.$message.success("修改成功");
      this.getUserList();
    },
    //编辑图片
    async handleSuccess(file, foodId) {
      const formData = new FormData();
      formData.append("files", file.raw);
      formData.append("foodId", foodId);

      await this.$http.post("/admin/foodupload", formData);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    // 搜索
    onSearch(value) {
      this.$refs.searchFormRef.validate(async (valid) => {
        if (valid) {
          const { name, state, type } = value;
          let stateV2 = state === "false" ? "0" : "1";
          const poiId = localStorage.getItem("poiId");
          const { data: res } = await this.$http.post(
            "/admin/foodCenter/searchList",
            {
              name,
              state: stateV2,
              type,
              poiId,
              page: this.currentPage,
              limit: this.pageSize,
            }
          );
          if (res.code !== 200) {
            this.$message.error("查询失败");
            return;
          }

          const newList = res.data;
          newList.forEach((item) => {
            item.state === "0" ? (item.state = false) : (item.state = true);
          });

          const { data: imageList } = await this.$http.post("/admin/images", {
            poiId: poiId,
          });

          const newListV2 = res.data.filter((item) => {
            const isFixList = imageList.data.filter(
              (j) => j.foodId === item.foodId
            );
            const isFixImags = isFixList.filter((i) => i.url);
            if (isFixList) {
              item.imgaes = isFixImags;
              return true;
            }
            return true;
          });

          newListV2.forEach((item) => {
            if (item.imgaes.length > 0) {
              item.imgaes = item.imgaes.map(
                (i) => "data:image/png;base64," + i.url
              );
            }
          });

          this.tableData = newListV2;
        }
      });
    },
    // 分页
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      // console.log(`当前页: ${val}`);
    },
    // 刷新
    async getUserList() {
      const poiId = window.localStorage.getItem("poiId");
      const { data: res } = await this.$http.get("/admin/foodCenter/getList", {
        params: {
          poiId,
        },
      });
      if (res.code !== 200) {
        this.$message.error("刷新失败");
        return;
      }
      const newList = res.data;
      newList.forEach((item) => {
        item.state === "0" ? (item.state = false) : (item.state = true);
      });

      const { data: imageList } = await this.$http.post("/admin/images", {
        poiId: poiId,
        isWhat: "1",
      });

      const newListV2 = res.data.filter((item) => {
        const isFixList = imageList.data.filter(
          (j) => j.foodId === item.foodId
        );
        const isFixImags = isFixList.filter((i) => i.url);
        if (isFixList) {
          item.imgaes = isFixImags;
          return true;
        }
        return true;
      });

      newListV2.forEach((item) => {
        if (item.imgaes.length > 0) {
          item.imgaes = item.imgaes.map(
            (i) => "data:image/png;base64," + i.url
          );
        }
      });

      console.log("===newListV2", newListV2);

      this.tableData = newListV2;
      this.page_num = this.tableData.length;
    },
    // 删除按钮
    onDelete(val) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: "true",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          // 接口
          this.delete(val);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 删除
    async delete(val) {
      const { data: res } = await this.$http.post(
        "/admin/foodCenter/deleteFood",
        {
          id: val.id,
        }
      );
      if (res.code !== 200) {
        this.$message.error("删除失败！");
        return;
      }
      this.getUserList();
    },
    onEdit(val) {
      this.EidtForm = val;
    },
    // 编辑
    async onEditBtn() {
      this.$refs.EidtFormRef.validate(async (valid) => {
        const { id, name, price, special, type, num, img } = this.EidtForm;
        // valid的值为true的时候代表表单验证成功
        if (valid) {
          const { data: res } = await this.$http.post(
            "/admin/foodCenter/editFood",
            {
              id,
              name,
              price,
              special,
              type,
              num,
              img,
            }
          );
          if (res.code !== 200) {
            this.$message.error("编辑失败！");
            return;
          }
          this.$message.success("编辑成功！");
          this.getUserList();
        }
      });
      this.getUserList();
    },

    // 点击新增按钮出发的事件
    handAdd() {
      this.isAddModelVisible = true;
    },
    // 新增菜品
    addSubmit() {
      this.$refs.AddFormRef.validate(async (valid) => {
        const { name, price, special, type, num, img } = this.AddForm;
        const poiId = localStorage.getItem("poiId");
        // valid的值为true的时候代表表单验证成功
        if (valid) {
          const { data: res } = await this.$http.post(
            "/admin/foodCenter/addFood",
            {
              poiId,
              name,
              price,
              special,
              type,
              num,
              img,
            }
          );
          console.log("==res", res);
          if (res.code !== 200) {
            this.$message.error("添加失败！");
            return;
          }
          this.$message.success("添加成功！");
          this.getUserList();
          // 后续对表单数据的处理
          this.isAddModelVisible = false;
        }
      });
    },
    // 搜索重置
    onSearchClear() {
      this.$refs.searchFormRef.resetFields();
      this.getUserList();
    },
  },
};
</script>
  
<style scoped>
.container {
  text-align: left;
}
.manage-header {
  display: flex;
  justify-content: space-between;
}
.block {
  margin-top: 20px;
}
</style>
  